package org.framework.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author：LCJ
 * @Description：
 * @Date：Create in 14:27 2021/5/1 0001
 */
@Slf4j
public class ClassUtil {

    public static final String FILE_PROTOCOL = "file";

    public static Set<Class<?>> extractPackageClass(String packagePath){

        //获取类的加载器
        ClassLoader classLoader = getClassLoader();
        //通过类加载器获取到加载的资源
        URL url = classLoader.getResource(packagePath.replace(".","/"));
        if(url == null){
            log.warn("unable to retrieve anything from package："+packagePath);
            return null;
        }
        //依据不同的资源类型，采用不同的方式获取资源的集合
        Set<Class<?>> classSet = null;
        if(url.getProtocol().equalsIgnoreCase(FILE_PROTOCOL)){
            classSet = new HashSet<Class<?>>();
            File packageDirectory = new File(url.getPath());
            extractClassFile(classSet,packageDirectory,packagePath);
        }
        return classSet;
    }

    /**
     * 获取目标下的所有class文件
     * @param classSet 装载目标类的集合
     * @param fileSource 文件或者目录
     * @param packagePath 包名
     */
    private static void extractClassFile(final Set<Class<?>> classSet, File fileSource, final String packagePath) {
        if(!fileSource.isDirectory()){
            return;
        }
        //如果是一个文件夹，则调用listFile方法获取文件夹下的文件或文件夹
        File[] files = fileSource.listFiles( new FileFilter() {
            public boolean accept(File pathname) {
                if(pathname.isDirectory()){
                    return true;
                }else{
                    //获取文件的绝对值路径
                    String absoluteFilePath = pathname.getAbsolutePath();
                    if(absoluteFilePath.endsWith(".class")){
                        //若是class文件，则直接加载
                        addToClassSet(absoluteFilePath);
                    }
                }
                return false;
            }

            //根据class文件的绝对值路径，获取并生成实例对象，并放入classSet
            private void addToClassSet(String absoluteFilePath) {
                //从class文件的绝对值路径中提取出包含package的类名
                absoluteFilePath = absoluteFilePath.replace(File.separator,".");
                String className = absoluteFilePath.substring(absoluteFilePath.indexOf(packagePath));
                className = className.substring(0,className.lastIndexOf("."));
                //通过反射机制获取对应的class对象并加入classSet
                Class clazz = loadClass(className);
                classSet.add(clazz);
            }
        });
        if(files != null){
            for (File f : files){
                //递归调用
                extractClassFile(classSet,f,packagePath);
            }
        }
    }

    /**
     * 获取classload
     * @return
     */
    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    public static Class<?> loadClass(String className){
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error("load class error",e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  实例化class
     * @param clazz
     * @param accessible
     * @param <T>
     * @return
     */
    public static <T> T newInstance(Class<?> clazz,boolean accessible){
        try {
            Constructor constructor =clazz.getDeclaredConstructor();
            constructor.setAccessible(accessible);
            return (T)constructor.newInstance();
        } catch (Exception e) {
            log.error("newInstance is error ",e);
            throw new RuntimeException();
        }
    }
}
